@file:JvmName("Main")

package net.jellygame.test

import com.github.brainlag.nsq.NSQConsumer
import com.github.brainlag.nsq.NSQProducer
import com.github.brainlag.nsq.lookup.DefaultNSQLookup
import com.github.brainlag.nsq.lookup.NSQLookup
import java.nio.charset.Charset
import java.util.concurrent.locks.Lock
import kotlin.concurrent.fixedRateTimer
import kotlin.concurrent.withLock


/**
 * Created by jianglu on 2017/7/13.
 */

val topic_name = "jellytest"
val N = 100000


fun main(args: Array<String>) {
    val mode = Integer.parseInt(args[0])

    if(0 == mode){
        val producer = NSQProducer().addAddress("localhost", 4150).start()
        val start1 = System.currentTimeMillis()

        for(i in 1..N){
            producer.produce(topic_name, "this is a message $i".toByteArray())
        }

        val end1 = System.currentTimeMillis()
        println("END")
        print(end1-start1)
    }
    else{
        val lookup = DefaultNSQLookup()
        var counter1 = 0
        val llock =  java.util.concurrent.locks.ReentrantLock()
        lookup.addLookupAddress("localhost", 4161)
        val  consumer = NSQConsumer(lookup, topic_name, "default", {
            llock.withLock { counter1++ }

            it.finished()
            if(counter1 < 20) {
                println(it.message.toString(Charset.defaultCharset()))
            }
            else if(0 == (counter1 % 100)){
                println("got  $counter1  msgs")
            }
        })

        fixedRateTimer(period = 2000, action = {
            println("got  $counter1  msgs")
        } )

        consumer.setMessagesPerBatch(10).start()
    }

}
